#include "PclContext.h"

#include "utils/FileUtil.h"

PclContext::PclContext() {}

PclContext& PclContext::get()
{
    static PclContext that;
    return that;
}

void PclContext::updateUI()
{
    vector<Camera> cameras;
    viewer_->getCameras(cameras);
    Camera active = cameras[0];
    viewer_->setCameraPosition(
        active.pos[0], active.pos[1], active.pos[2], active.focal[0],
        active.focal[1], active.focal[2], active.view[0], active.view[1],
        active.view[2], 0
    );
    qvtkWidget_->update();
}

void PclContext::refreshModel(PclDefaultModel& model)
{
    model.cameras().clear();
    viewer_->getCameras(model.cameras());
}

void PclContext::updateCamera(PclDefaultModel& model, int index)
{
    if (index < 0 || index >= model.cameras().size()) {
        return;
    }
    Camera active = model.cameras()[index];
    viewer_->setCameraPosition(
        active.pos[0], active.pos[1], active.pos[2], active.focal[0],
        active.focal[1], active.focal[2], active.view[0], active.view[1],
        active.view[2], index
    );
    qvtkWidget_->update();
}

void PclContext::updateCoordinate(PclDefaultModel& model)
{
    if (model.showCoordinate()) {
        viewer_->removeAllCoordinateSystems();
        viewer_->addCoordinateSystem(model.coordinateScale());
    }
    updateUI();
}

void PclContext::showCoordinate(PclDefaultModel& model)
{
    if (model.showCoordinate()) {
        viewer_->addCoordinateSystem(model.coordinateScale());

    } else {
        viewer_->removeAllCoordinateSystems();
    }
    updateUI();
}

void PclContext::updatePointSize(PclDefaultModel& model)
{
    viewer_->setPointCloudRenderingProperties(
        pcl::visualization::PCL_VISUALIZER_POINT_SIZE, model.pointSize(),
        "cloud"
    );
    updateUI();
}
void PclContext::updatePointColor(PclDefaultModel& model)
{
    PointCloudColorHandlerCustom<PointT> dataColor(
        cloud_, model.pointColor().red(), model.pointColor().green(),
        model.pointColor().blue()
    );
    viewer_->updatePointCloud(cloud_, dataColor, "cloud");
    updateUI();
}

void PclContext::updateBackgroundColor(PclDefaultModel& model)
{
    viewer_->setBackgroundColor(
        model.backgroundColor().red() / 256.0,
        model.backgroundColor().green() / 256.0,
        model.backgroundColor().blue() / 256.0
    );
    updateUI();
}

void PclContext::close()
{
    PclDefaultModel::get().save();
}
